package cn.iocoder.yudao.module.promotion.groupon.service.admin;

import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.business.basic.dao.query.CoreQueryWrapper;
import cn.iocoder.yudao.framework.business.basic.pojo.vo.ShopSimpleVO;
import cn.iocoder.yudao.framework.business.basic.service.CrudService;
import cn.iocoder.yudao.framework.business.basic.service.impl.BaseService;
import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
import cn.iocoder.yudao.framework.common.exception.Assertions;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.region.RegionUtils;
import cn.iocoder.yudao.framework.region.enums.RegionDataSet;
import cn.iocoder.yudao.module.api.infrastructure.config.ConfigApiV2;
import cn.iocoder.yudao.module.api.shop.category.eums.ShopCategoryCodeEnum;
import cn.iocoder.yudao.module.api.shop.info.ShopInfoApi;
import cn.iocoder.yudao.module.api.shop.info.dto.ShopInfoDTO;
import cn.iocoder.yudao.module.promotion.gift.service.admin.GiftActivityService;
import cn.iocoder.yudao.module.promotion.groupon.dao.GrouponPackageMapper;
import cn.iocoder.yudao.module.promotion.groupon.pojo.dto.AdminGrouponPackageGiftAddDTO;
import cn.iocoder.yudao.module.promotion.groupon.pojo.dto.AdminGrouponPackageGiftRemoveDTO;
import cn.iocoder.yudao.module.promotion.groupon.pojo.dto.AdminGrouponPackageQueryDTO;
import cn.iocoder.yudao.module.promotion.groupon.pojo.dto.AdminGrouponPackageSaveDTO;
import cn.iocoder.yudao.module.promotion.groupon.pojo.po.GrouponPackage;
import cn.iocoder.yudao.module.promotion.groupon.pojo.vo.AdminGrouponPackageVO;
import cn.iocoder.yudao.module.promotion.groupon.service.app.AppGrouponProductService;
import jakarta.annotation.Nonnull;
import jakarta.annotation.Nullable;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import java.util.*;

import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertList;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserLastShopId;

/**
 * <pre>
 * OOoO0OOoO0OOOooo0oOOOO0OOOOO0oooOO0ooOOO0Ooooo0OOOOo0ooooO0OOooo0Ooooo0OOOOO
 *  这里是文件说明
 * OOoO0OOoO0OOOooo0oOOOO0OOOOO0oooOO0ooOOO0Ooooo0OOOOo0ooooO0OOooo0Ooooo0OOOOO
 * </pre>
 *
 * @author 山野羡民（1032694760@qq.com）
 * @since 2025/01/13
 */
@Service
@Validated
public class AdminGrouponPackageServiceImpl extends BaseService<GrouponPackage, AdminGrouponPackageVO, AdminGrouponPackageQueryDTO> implements AdminGrouponPackageService, CrudService<GrouponPackage, AdminGrouponPackageVO, AdminGrouponPackageSaveDTO, AdminGrouponPackageQueryDTO> {
    @Resource
    private GrouponPackageMapper grouponPackageMapper;

    @Resource
    @Lazy // 延迟加载，避免循环依赖
    private AppGrouponProductService appGrouponProductService;
    @Resource
    @Lazy // 延迟加载，避免循环依赖
    private GiftActivityService giftActivityService;

    @Resource
    @Lazy // 延迟加载，避免循环依赖
    private ShopInfoApi shopInfoApi;
    @Resource
    @Lazy // 延迟加载，避免循环依赖
    private ConfigApiV2 configApiV2;

    @Override
    public GrouponPackageMapper getInjectedMapper() {
        return grouponPackageMapper;
    }

    @Nonnull
    @Override
    protected CoreQueryWrapper<GrouponPackage> buildQueryWrapper(AdminGrouponPackageQueryDTO param) {
        CoreQueryWrapper<GrouponPackage> wrapper = super.buildQueryWrapper(param);
        wrapper.eq(StrUtil.isNotBlank(param.getType()), "type", param.getType());
        wrapper.eqIfPresent("shop_id", param.getShopId());
        wrapper.likeIfPresent("name", param.getName());
        wrapper.leIfPresent("min_people", param.getPeople());
        wrapper.geIfPresent("max_people", param.getPeople());
        wrapper.eqIfPresent("enabled", param.getEnabled());
        return wrapper;
    }

    @Override
    public GrouponPackage convertToEntity(AdminGrouponPackageSaveDTO param) {
        return BeanUtils.toBean(param, GrouponPackage.class);
    }

    @Override
    public List<AdminGrouponPackageVO> convertToViewObject(@Nonnull List<GrouponPackage> entities) {
        List<AdminGrouponPackageVO> respVOS = convertList(entities, this::convertToViewObject);
        Set<Long> shopIds = convertSet(entities, GrouponPackage::getShopId);
        Map<Long, ShopSimpleVO> shops = shopInfoApi.getShopSimpleMap(shopIds);
        for (AdminGrouponPackageVO respVO : respVOS) {
            respVO.setShop(shops.getOrDefault(respVO.getShopId(), ShopSimpleVO.EMPTY));
            RegionUtils.autoAssignCounty(RegionDataSet.ONLY_LATEST, respVO.getShop().getCountyCode(), respVO.getShop());
            respVO.setDeductUnitPrice(configApiV2);
        }
        return respVOS;
    }

    @Override
    public AdminGrouponPackageVO getDetail(Long id) {
        AdminGrouponPackageVO respVO = super.getDetail(id);
        respVO.setGiftActivities(giftActivityService.getList(respVO.getGiftActivityIds()));
        respVO.setProducts(appGrouponProductService.getListByPackageId(id));
        respVO.setDeductUnitPrice(configApiV2);
        return respVO;
    }

    @Override
    public void beforeCreate(GrouponPackage entity, @Nullable Long userId) {
        ShopInfoDTO shopInfo = shopInfoApi.getShopInfo(getLoginUserLastShopId());
        Assertions.isTrue(shopInfo != null, "当前用户没有店铺");
        Assertions.isTrue(CommonStatusEnum.isEnable(shopInfo.getEnabled()), "店铺已被封禁：" + shopInfo.getName());
        entity.setId(null);
        entity.setShopId(shopInfo.getId());
        String categoryCode = shopInfo.getCategoryCode();
        Assertions.isTrue(StrUtil.isNotBlank(categoryCode), "店铺主营类目无效：" + shopInfo.getId());
        Assertions.isTrue(ShopCategoryCodeEnum.isO2o(categoryCode), "团购套餐只支持生活商圈的商家");
        entity.setType(categoryCode);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean delete(Long shopId, Long id) {
        grouponPackageMapper.deleteById(id, shopId);
        return appGrouponProductService.delete(shopId, id);
    }

    @Override
    public boolean update(AdminGrouponPackageSaveDTO param) {
        GrouponPackage entity = validateExists(param.getId());
        GrouponPackage updateObj = BeanUtils.toBean(param, GrouponPackage.class);
        updateObj.setId(entity.getId());
        int rows = grouponPackageMapper.updateById(updateObj);
        return rows > 0;
    }

    @Override
    public boolean addGifts(AdminGrouponPackageGiftAddDTO param) {
        AdminGrouponPackageVO respVO = getDetail(param.getId());
        List<Long> ids = respVO.getGiftActivityIds();
        if (ids == null) {
            ids = new ArrayList<>();
        }
        ids.addAll(param.getGiftActivityIds());
        GrouponPackage updateObj = new GrouponPackage();
        updateObj.setId(respVO.getId());
        updateObj.setGiftActivityIds(new HashSet<>(ids).stream().toList());
        int rows = grouponPackageMapper.updateById(updateObj);
        return rows > 0;
    }

    @Override
    public boolean removeGift(AdminGrouponPackageGiftRemoveDTO param) {
        AdminGrouponPackageVO respVO = getDetail(param.getId());
        List<Long> ids = new ArrayList<>();
        if (respVO.getGiftActivityIds() != null) {
            for (Long id : respVO.getGiftActivityIds()) {
                if (!Objects.equals(id, param.getGiftActivityId())) {
                    ids.add(id);
                }
            }
        }
        GrouponPackage updateObj = new GrouponPackage();
        updateObj.setId(respVO.getId());
        updateObj.setGiftActivityIds(new HashSet<>(ids).stream().toList());
        int rows = grouponPackageMapper.updateById(updateObj);
        return rows > 0;
    }

}
